package sv.gob.mh.dgii.service.ed;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sv.gob.mh.dgii.dao.ed.EdDetMovilDao;


@Service
public class EdDetMovilServiceImpl implements EdDetMovilService {
	
	@Autowired
	private EdDetMovilDao edDetMovilDao;
	
	private String baseDir = File.separator + "net_dgii_det_movil";
	
	private String fileExt = ".zip";
	
	private String checkFileExt = ".ok";
	
	public void generarArchivos(String nit, String periodo, String usuario, String email) {
		edDetMovilDao.generarArchivos(nit, periodo, usuario, email);
	}
	
	public byte[] getArchivo(String nit, String periodo) throws IOException {
		File file = obtainFile(nit, periodo);
		return obtainFileContent(file);
	}
	
	protected File obtainFile(String nit, String periodo) {
		StringBuffer sb = new StringBuffer(baseDir);
		sb.append(File.separator);
		sb.append(nit);
		sb.append(periodo);
		sb.append(fileExt);
		return new File(sb.toString());
	}
	
	private byte[] obtainFileContent(File file) throws IOException {
		FileInputStream fis = new FileInputStream(file);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		for (int c = fis.read(); c != -1; c = fis.read()) {
			baos.write(c);
		}
		baos.close();
		byte bytes[] = baos.toByteArray();
		fis.close();
		baos.close();
		return bytes;
	}
	
	public boolean senseOkFile(String nit, String periodo){
		boolean retval = true;
		StringBuffer sb = new StringBuffer(baseDir);
		sb.append(File.separator);
		sb.append(nit);
		sb.append(periodo);
		//sb.append(fileExt);
		sb.append(checkFileExt);
		retval = (new File(sb.toString())).exists();
		return retval;
	}
	
	public Long getMovilId(String nitAgt, String periodo, String estado) {
		try {
			return this.edDetMovilDao.getMovilId(nitAgt, periodo, estado);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	
	
	public String getBaseDir() {
		return baseDir;
	}
	public void setBaseDir(String baseDir) {
		this.baseDir = baseDir;
	}
	public String getFileExt() {
		return fileExt;
	}
	public void setFileExt(String fileExt) {
		this.fileExt = fileExt;
	}

}
